# -*- coding: utf-8 -*-
"""
 @Time    : 2021/1/26 下午2:25
 @Author  : tgy
 
"""

print('1111')
class Node:
    __slots__ = ['children', 'val']

    def __init__(self, val):
        self.val = val
        self.children = []

    def add_child(self, child):
        ...
        if not child or not isinstance(child, Node):
            raise TypeError('child must Node type')
        self.children.append(child)

    def __iter__(self):
        return iter(self.children)

    # def deep_fist(self):
    #     yield self
    #     for child in self.children:
    #         yield from child.deep_fist()
    def deep_fist(self):
        return NodeIter(self)

    @staticmethod
    def test01():
        print('2222')

class NodeIter:
    __slots__ = ['node', 'children_iter', 'child_iter']

    def __init__(self, node: Node):
        ...
        self.node = node
        self.children_iter = None
        self.child_iter = None

    def __iter__(self):
        return self

    def __next__(self):
        if self.children_iter is None:
            self.children_iter = iter(self.node)
            return self.node
        elif self.child_iter:
            try:
                return next(self.child_iter)
            except StopIteration:
                self.child_iter = None
                return next(self)
        else:
            self.child_iter = next(self.children_iter).deep_fist()
            return next(self)


if __name__ == '__main__':
    ...
    root = Node(1)
    root.add_child(Node(2))
    node3 = Node(3)
    root.add_child(node3)
    node3.add_child(Node(4))

    for node in root.deep_fist():
        print(node.val)
